package com.mediatime;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.widget.Toast;

public class listenerservice extends Service implements OnInitListener {

	private static final int MY_DATA_CHECK_CODE = 0;
	private listenerReceiver receiver;
	private TextToSpeech tts;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		receiver = new listenerReceiver();
		IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
		registerReceiver(receiver, filter);
		
		tts = new TextToSpeech(this, this);
		tts.speak("I am your most beautiful girl !", TextToSpeech.QUEUE_ADD, null);
//		Intent checkIntent = new Intent();
//		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
//		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(receiver);
		super.onDestroy();
	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				// success, create the TTS instance
				tts = new TextToSpeech(this, this);
			} else {
				// missing data, install it
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
			}
		}

	}

	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
			Toast.makeText(getApplicationContext(),
					"Text-To-Speech engine is initialized", Toast.LENGTH_LONG)
					.show();
		} else if (status == TextToSpeech.ERROR) {
			Toast.makeText(getApplicationContext(),
					"Error occurred while initializing Text-To-Speech engine",
					Toast.LENGTH_LONG).show();
		}
	}
	
	class listenerReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)){
				if(intent.hasExtra("state")){
					int state = intent.getIntExtra("state", 0);
					if(state==0)
						Toast.makeText(getApplicationContext(), "not headset", Toast.LENGTH_SHORT).show();
					else if(state ==1)
						Toast.makeText(getApplicationContext(), "headset connect",Toast.LENGTH_SHORT).show();
				}
						
			}
		}
		
	}
}
